<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use phpDocumentor\Reflection\Types\This;
use Illuminate\Support\Facades\Log;

class Coll extends Model
{
    use HasFactory;

    protected $guarded = [''];

    //收藏或者取消收藏
    public function collOrCancel($cover_id, $user_id)
    {
        $cover = Cover::query()->where('id',$cover_id)->first();
        if (!$cover) return false;

        if ($cover->status != 1) false;

        try{
            $coll = $this->query()->where(['user_id' => $user_id, 'cover_id' => $cover_id])->first();

            if ($coll){
                if ($coll->state == 1){
                    $coll->state = 0;
                    $cover->decrement('coll');
                }else{
                    $coll->state = 1;
                    $cover->increment('coll');
                }
                $coll->save();
            }else{
                $this->query()->create([
                    'user_id' => $user_id,
                    'cover_id' => $cover_id,
                    'state' => 1,
                ]);

                $cover->increment('coll');
            }
            return $this;
        }catch (\Exception $exception){
            Log::channel('daily')->debug($exception->getMessage());
            return false;
        }
    }
}
